﻿using System;
using System.Linq;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Windows.Forms;

using QuickTuner.Properties;
using QuickTuner.Util;

namespace QuickTuner
{
    public partial class editForm : Form
    {
        private readonly StationList _list;


        public editForm(StationList theList)
        {
            InitializeComponent();

            this.Icon = Resources.editFormIcon;
            this.Location = Program.Config.editFormLocation;
            this.Size = Program.Config.editFormSize;

            _list = theList;
            _list.SortUserOrdinal();

            stationsSource.DataSource = _list;
        }

        public void RefreshRadioState()
        {
            stationsSource.ResetBindings(false);
        }


        // Event handlers _______________________________________________________________

        private void addButton_Click(object sender, EventArgs e) { stationsSource.AddNew(); }

        private void deleteButton_Click(object sender, EventArgs e)
        {
            if (stationsSource.Count > 0)
                stationsSource.RemoveCurrent();
        }

        private void upButton_Click(object sender, EventArgs e)
        {
            // find current station
            var current = stationsSource.Current as Station;
            if (current == null) return;

            // find the station above current station
            var currentIdx = stationsSource.Position;
            var idxAbove = currentIdx - 1;
            if (idxAbove < 0) return;

            var stationAbove = (Station)stationsSource[idxAbove];

            // swap user ordinal value and refresh binding
            stationsSource.SuspendBinding();

            var temp = current.UserOrdinal;
            current.UserOrdinal = stationAbove.UserOrdinal;
            stationAbove.UserOrdinal = temp;

            _list.SortUserOrdinal();
            stationsSource.ResumeBinding();
            stationsGrid.Refresh();

            // reset icons of both swapped rows
            resetRowIcon(stationsGrid.Rows[currentIdx]);
            resetRowIcon(stationsGrid.Rows[idxAbove]);

            // move the selection up along with the new station position
            var columnIdx = stationsGrid.SelectedCells[0].ColumnIndex;
            stationsSource.Position = idxAbove;
            stationsGrid.SelectedCells[0].Selected = false;
            stationsGrid.Rows[idxAbove].Cells[columnIdx].Selected = true;
        }

        private void downButton_Click(object sender, EventArgs e)
        {
            // find current station
            var current = stationsSource.Current as Station;
            if (current == null) return;

            // find the station below current station
            var currentIdx = stationsSource.Position;
            var idxBelow = currentIdx + 1;
            if (idxBelow >= stationsSource.Count) return;

            var stationBelow = (Station)stationsSource[idxBelow];

            // swap user ordinal value and refresh binding
            stationsSource.SuspendBinding();

            var temp = current.UserOrdinal;
            current.UserOrdinal = stationBelow.UserOrdinal;
            stationBelow.UserOrdinal = temp;

            _list.SortUserOrdinal();
            stationsSource.ResumeBinding();
            stationsGrid.Refresh();

            // reset icons of both swapped rows
            resetRowIcon(stationsGrid.Rows[currentIdx]);
            resetRowIcon(stationsGrid.Rows[idxBelow]);

            // move the selection down along with the new station position
            var columnIdx = stationsGrid.SelectedCells[0].ColumnIndex;
            stationsSource.Position = idxBelow;
            stationsGrid.SelectedCells[0].Selected = false;
            stationsGrid.Rows[idxBelow].Cells[columnIdx].Selected = true;
        }

        private void importListButton_Click(object sender, EventArgs e)
        {
            // load saved path or default to my documents
            var path = Program.Config.lastOpenPath;
            if (string.IsNullOrEmpty(path))
                path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

            openDialog.InitialDirectory = path;

            // show the open file dialog
            if (openDialog.ShowDialog() == DialogResult.Cancel) return;

            // save the path settings
            Program.Config.lastOpenPath = Path.GetDirectoryName(openDialog.FileName);

            // load list of stations from the selected file
            var fs = File.OpenRead(openDialog.FileName);

            var importList = StationList.LoadFrom(fs);

            fs.Close();
            fs.Dispose();

            foreach (var station in importList)
                stationsSource.Add(station);
        }

        private void exportListButton_Click(object sender, EventArgs e)
        {
            // load saved path or default to my documents
            var path = Program.Config.lastSavePath;
            if (string.IsNullOrEmpty(path))
                path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

            saveDialog.InitialDirectory = path;

            // show the save file dialog
            if (saveDialog.ShowDialog() == DialogResult.Cancel) return;

            // save the path settings
            Program.Config.lastSavePath = Path.GetDirectoryName(saveDialog.FileName);

            // save list of stations to selected file
            var fs = File.OpenWrite(saveDialog.FileName);

            _list.SaveXmlTo(fs);

            fs.Close();
            fs.Dispose();
        }

        private void saveButton_Click(object sender, EventArgs e) { this.Close(); }

        private void editForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            // make sure any editing progress is commited before closing the form
            if (stationsGrid.IsCurrentCellInEditMode)
                stationsGrid.EndEdit();
        }


        // data binding events __________________________________________________________

        private void stationsSource_AddingNew(object sender, AddingNewEventArgs e)
        {
            e.NewObject = new Station {
                Title = "New station",
                StationUrl = "http://put/url/here",
                UserOrdinal = _list.Max(s => s.UserOrdinal)
            };
        }

        private void stationsGrid_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            stationsGrid.Rows.ForEach(r => resetRowIcon((DataGridViewRow)r));
        }

        private void shareListButton_Click(object sender, EventArgs e) { }

        private void gotoWebsiteButton_Click(object sender, EventArgs e) { Process.Start(@"http://www.quicktuner.net/"); }

        // helpers ______________________________________________________________________

        private void resetRowIcon(DataGridViewRow row)
        {
            // get the attached station
            var station = row.DataBoundItem as Station;
            if (station == null) return;

            // get the first cell
            var cell = row.Cells[0];

            // assign the "empty" image first in case a favicon is not found.

            cell.Value = Resources.musicImage;

            // download image and if success, use it as the icon
            IconCache.BeginGetIcon(station, ar => {
                var img = IconCache.EndGetIcon(ar);
                if (img != null) cell.Value = img;
            });
        }
    }
}